package com.rental.common.config.redisson;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.Data;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Data
//@Configuration
//@ConfigurationProperties(prefix = "spring.data.redis")
public class RedissonConfig {
    // redis 配置
    private String host; // 主机
    private String port; // 端口
    private String password; // 密码
    private Integer timeout; // 超时时间
    private static String ADDREDIS_PREFIX = "redis://"; // redisson 前缀

    /**
     * redisson 配置
     * @return RedissonClient
     */
    @Bean
    public RedissonClient redissonClient() {
        // 声明redisson配置
        Config config = new Config();
        // 从配置文件中获取的主机为空时抛出异常
        if (StringUtils.isBlank(host)) throw new RuntimeException("redisson error, host is null");
        //设置redisson单例服务的地址
        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress(ADDREDIS_PREFIX + host + ":" + port);
        // 如果有密码则设置密码
        if (StringUtils.isNotBlank(password)) singleServerConfig.setPassword(password);
        // 创建RedissonClient并返回
        return Redisson.create(config);
    }
}
